package com.endoc.phtotapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.endoc.phtotapplication.activity.BaseActivity;
import com.endoc.phtotapplication.activity.DeviceImfSetActivity;
import com.endoc.phtotapplication.activity.UserDetailActivity;
import com.endoc.phtotapplication.activity.UserManagerActivity;
import com.endoc.phtotapplication.activity.VerifyActivity;
import com.endoc.phtotapplication.litepal.Person;
import com.endoc.phtotapplication.litepal.UploadPerson;
import com.endoc.phtotapplication.utils.Base64Utils;
import com.endoc.phtotapplication.utils.BitMapUts;
import com.endoc.phtotapplication.utils.ComPressBitmapUtils;
import com.endoc.phtotapplication.utils.SharePrefrencesUtils;
import com.endoc.phtotapplication.utils.StatusBarUtil;
import com.endoc.phtotapplication.utils.StringUtils;
import com.endoc.phtotapplication.utils.VerifyUtils;
import com.endoc.phtotapplication.utils.YUVutils;
import com.hikvision.face.HikFRAAPI;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private String TAG = "hikFRDemo";
    private CameraHandle mCamHandle = null;
    private SurfaceView mPrevSurface = null;
    private HikFRAAPI mFRAProc = null;

    private FRAListener mListener = null;
    //建模模型需要存放在sdcard根目录，当前位置在assets文件夹下
    private String mModelPath = "/sdcard/DFR_Model.bin";

    private Button mStartBT = null;
    private Button mCaptureBT = null;
    private Button mAddFaceBt = null;
    private Button mFaceLibShow = null;
    private ImageView mFaceImg = null;
    private ImageView mFaceCap = null;
    private ImageView mFaceAddShow = null;
    private ImageView mLeft = null;
    private ImageView mRight = null;
    private TextView mFaceId = null;
    private TTSBroadcast mSpeak = null;
    private FaceRectView mFaceRect = null;

    private Context mContex;

    private Bitmap mCurFaceBm = null;
    private String mLastFaceId = null;

    private DeviceOrientationListion mDevOrListion = null;
    private int mDeviRotation = 0;
    //动态权限申请
 /*   private static String[] PERMISSIONS_ALLOC = {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.MODIFY_AUDIO_SETTINGS,

    };*/

    private byte[] IDmodelData = new byte[300];
    long mSuccessTime =0;//上次比对成功的时间
    private static final int MSGCB_FC = 0;
    private static final int MSGCB_FR = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSGCB_FC) {
                String msgData = (String) msg.obj;
                String[] sArray = msgData.split("#");

                mFaceId.setPivotX(mFaceId.getWidth() / 2);
                mFaceId.setPivotY(mFaceId.getHeight() / 2);
                mFaceId.setRotation((mDeviRotation == 0 ? 0 : (360 - mDeviRotation)));
                DecimalFormat df = new DecimalFormat("###.##");
                mFaceId.setText(("人员：" + sArray[2] + "\n相似度：" + df.format(Float.parseFloat(sArray[0]) / 10) + "%"));
                //Log.d(TAG, "1---------->>smilar:" + sArray[0] + " lib:" + sArray[1] + " humId:" + sArray[2] + " path:" + sArray[3]);
                Log.d(TAG, "触发识别...");
                if (Float.parseFloat(sArray[0]) >= 700) {//如果匹配度大于等于80

                    long  currentTime=Calendar.getInstance().getTimeInMillis();
                    if (mLastFaceId != null && mLastFaceId.equals(sArray[2])&& currentTime-mSuccessTime<=5000&&mSuccessTime!=0) {
                        return;
                    }
                    Log.d(TAG, "\n触发识别相似度：" + df.format(Float.parseFloat(sArray[0]) / 10));
                    mSuccessTime =currentTime;
                    mLastFaceId = sArray[2];

                    mSpeak.playText(sArray[2]);

                    File file = new File(sArray[3]);
                    Log.d(TAG, "file===" + file.getAbsolutePath());
                    if (file.exists()) {
                        //Bitmap bm = BitmapFactory.decodeFile(sArray[3]);
                       /* RoundedBitmapDrawable rdBm = RoundedBitmapDrawableFactory.create(getResources(), sArray[3]);
                        rdBm.setCornerRadius(20);

                        mFaceImg.setPivotX(mFaceImg.getWidth() / 2);
                        mFaceImg.setPivotY(mFaceImg.getHeight() / 2);
                        mFaceImg.setRotation((mDeviRotation == 0 ? 0 : (360 - mDeviRotation)));
                        mFaceImg.setImageDrawable(rdBm);*/


                        //那么执行上传操作
                        Log.d(TAG, "开始上传");
                        //String bitmapToBase64 = Base64Utils.bitmapToBase64(mRotatedBitmap);


//                        Bitmap bitmap = Bitmap.createBitmap(mPrevSurface.getWidth(), mPrevSurface.getHeight(), Bitmap.Config.ARGB_8888);
//                        Canvas bitCanvas = new Canvas(bitmap);
//                        mPrevSurface.doDraw(bitCanvas);
//                        String bitmapToBase64 = Base64Utils.bitmapToBase64(mPrevSurface);
                        //此处应该通过名字查询数据库,再把id放进去


                        //提示匹配成功
                        List<Person> personList = LitePal.where("personID = ?", mLastFaceId).find(Person.class);
                        if (personList.size() != 0) {
                            //卸载重装会导致数据库没有了  但是本地存的图片还在  导致gg
                            //show face ID
                            Log.d(TAG,"数据库找到了对应的id");
                            mFaceRect.drawFaceInfo(personList.get(0).getName());
                            VerifyUtils.verifyResult(MainActivity.this, findViewById(R.id.rl_root), personList.get(0).getName(), true);
                            String bitmapToBase64 = Base64Utils.bitmapToBase64(faceBitmap);
                            WorkUtils.getInstance(mContext).startUpLoad(sArray[2], "192.168.100.200", bitmapToBase64);
                        }
                    /*    new Thread(new Runnable() {
                            @Override
                            public void run() {

                            }
                        }).start();*/
                    }

                } else {
                    VerifyUtils.verifyResult(MainActivity.this, findViewById(R.id.rl_root), "fail", false);
                }
                // Log.d(TAG, "2---------->>");
            } else if (msg.what == MSGCB_FR) {
                Log.d(TAG, "msg.what == MSGCB_FR");
                String metaData = (String) msg.obj;
                // Log.d(TAG, "3---------->> Show current face rect: " + metaData);
                Matrix matrix = new Matrix();
                matrix.postRotate(90);
                Bitmap rotatedBitmap = Bitmap.createBitmap(mCurFaceBm, 0, 0, mCurFaceBm.getWidth(), mCurFaceBm.getHeight(), matrix, true);
                RoundedBitmapDrawable rdBm = RoundedBitmapDrawableFactory.create(getResources(), rotatedBitmap);
                rdBm.setCornerRadius(20);
                mFaceCap.setImageDrawable(rdBm);
                // Log.d(TAG, "4--------->>");
            }
        }
    };
    //人脸比对的时候抓取的数据


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
            //StatusBarUtil.setStatusBarColor(this, Color.parseColor("#FFFFFF"));
        }
        mContex = this;

        //allocPermission(new String[]{});
        //startActivity(new Intent(MainActivity.this,MyPhotoActivity.class));
        //startActivity(new Intent(MainActivity.this, UserDetailActivity.class));
        //startActivity(new Intent(MainActivity.this, VerifyActivity.class));
        //finish();

        //开启定时网络请求

        mFaceRect = findViewById(R.id.faceRect);
        mSpeak = new TTSBroadcast(MainActivity.this);

        mFaceImg = (ImageView) findViewById(R.id.humImg);
        mFaceId = (TextView) findViewById(R.id.humId);

        mFaceCap = (ImageView) findViewById(R.id.faceCap);


        /* 启动相机预览, 加载人脸数据库，启动算法*/
        mStartBT = (Button) findViewById(R.id.start);
        mStartBT.setOnClickListener(this);

        /* 获取一帧数据*/
        mCaptureBT = (Button) findViewById(R.id.capture);
        mCaptureBT.setOnClickListener(this);

        /* 加载人脸数据*/
        mAddFaceBt = (Button) findViewById(R.id.addface);
        mAddFaceBt.setOnClickListener(this);

        /* 显示人脸库*/
        mFaceLibShow = findViewById(R.id.show);
        mFaceLibShow.setOnClickListener(this);

        /* 显示添加人脸俘获数据*/
        mFaceAddShow = findViewById(R.id.AddFaceImg);


        mLeft = findViewById(R.id.im_left);
        mLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, UserManagerActivity.class));
            }
        });

        mRight = findViewById(R.id.im_right);
        mRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DeviceImfSetActivity.class);
                intent.putExtra(StringUtils.deviceImfor, true);
                startActivity(intent);
            }
        });
      findViewById(R.id.im_change).setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if (mCamHandle != null) {
                  mCamHandle.switchCamera();
              }
          }
      });

        /* 监听设备方向*/
        mDevOrListion = new DeviceOrientationListion(this, SensorManager.SENSOR_DELAY_NORMAL);
        if (mDevOrListion.canDetectOrientation()) {
            mDevOrListion.enable();
        } else {
            Log.e(TAG, "Can't DetectOrientation");
        }
        allocPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});
        //init();
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {

    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume===");
        allocPermission(new String[]{Manifest.permission.CAMERA});

        //startCamera();
    }


   /* private void readFileFromAssets() throws IOException {
        File file = new File(mModelPath);//建模模型
        if (file.exists()) {//如果模型存在
            return;
        }
        //否则就写到sdcard中
        InputStream iStream = getAssets().open("DFR_Model.bin");
        byte[] buffer = new byte[1024];
        int count = iStream.read(buffer);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(buffer, 0, count);
        fos.close();
    }*/


    public static void copyFilesFromAssets(Context context, String assetsPath, String savePath) {
        try {
            String fileNames[] = context.getAssets().list(assetsPath);// 获取assets目录下的所有文件及目录名
            if (fileNames.length > 0) {// 如果是目录
                File file = new File(savePath);
                file.mkdirs();// 如果文件夹不存在，则递归
                for (String fileName : fileNames) {
                    copyFilesFromAssets(context, assetsPath + "/" + fileName,
                            savePath + "/" + fileName);
                }
            } else {// 如果是文件
                InputStream is = context.getAssets().open(assetsPath);
                FileOutputStream fos = new FileOutputStream(new File(savePath));
                byte[] buffer = new byte[1024];
                int byteCount = 0;
                while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                    // buffer字节
                    fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
                }
                fos.flush();// 刷新缓冲区
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 删除文件或文件夹
     *
     * @param directory
     */
    public static void delAllFile(File directory) {
        if (!directory.isDirectory()) {
            directory.delete();
        } else {
            File[] files = directory.listFiles();

            // 空文件夹
            if (files.length == 0) {
                directory.delete();
                System.out.println("删除" + directory.getAbsolutePath());
                return;
            }

            // 删除子文件夹和子文件
            for (File file : files) {
                if (file.isDirectory()) {
                    delAllFile(file);
                } else {
                    file.delete();
                    System.out.println("删除" + file.getAbsolutePath());
                }
            }

            // 删除文件夹本身
            directory.delete();
            System.out.println("删除" + directory.getAbsolutePath());
        }
    }

    public void init() {
        Log.d(TAG, "init");
        mPrevSurface = (SurfaceView) findViewById(R.id.surfaceView);

        //先把建模模型给弄到sdcard中
        if (!new File(mModelPath).exists()) {
            copyFilesFromAssets(this, "DFR_Model.bin", mModelPath);
        }

        mFRAProc = new HikFRAAPI();
        mListener = new FRAListener();
        mFRAProc.setListener(mListener);

        mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_FACE_MANAGE, "1");
        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.HIK_FRA_KEY_NEED_FQFL, "1");
        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.HIK_FRA_KEY_LIVE, "0.6");
        //人脸缓冲区大小默认100000张；
        mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_POOL_KEY_CAP, "10000");
        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_MULTI_THREAD, "1");
        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_EXT_RGB_BUFF, "1");
        //初始化建模模型
        //int init = mFRAProc.init(640, 480, HikFRAAPI.YUV_FORMAT.YUV_NV21, mModelPath);
        int init = mFRAProc.init(480, 640, HikFRAAPI.YUV_FORMAT.YUV_NV21, mModelPath);
        Log.i(TAG, "mFRAProc.init : " + init);
        //设置旋转角度，角度错误会导致识别失败
        mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_270);

        //判断是不是第一次进入app
        Boolean aBoolean = (Boolean) SharePrefrencesUtils.getParam(mContext, StringUtils.isFirst, true);
        File file = new File(StringUtils.FilePath);
        if (aBoolean) {//如果是那么就删除所有的人脸
            SharePrefrencesUtils.setParam(mContext, StringUtils.isFirst, false);
            if (file.exists()) {//如果人脸数据库文件夹存在
                delAllFile(file);//删除文件
                Log.d(TAG, "delAllFile(file)");
            }
        }

        if (!file.exists()) {
            file.mkdirs();
            Log.d(TAG, " file.mkdirs()");
        }
        //加载人脸数据库到缓冲区，即可实现1VN。
        mFRAProc.loadFaceData(1, StringUtils.FilePath, "/sdcard/facelib/database.bin", "facetest");
        //初始化数据库
        allocPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
        /*LitePal.getDatabase();
        WorkUtils.getInstance().startTimer(mFRAProc);*/
    }

    //抓取的脸部数据回调接口
    ImageDateInter imageDateInter = new ImageDateInter() {
        @Override
        public void getImageDate(Bitmap imageData,int result) {
            faceBitmap = imageData;
        }
    };
    Bitmap faceBitmap;//人脸识别接口
    int cameraId = 0;//记录上次摄像头打开方向，暂时还没用到
    public void startCamera() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                /*    Log.d(TAG, "start Camera preview!");
                    mPrevSurface = (SurfaceView) findViewById(R.id.surfaceView);
                    mFRAProc = new HikFRAAPI();
                    mListener = new FRAListener();
                    mFRAProc.setListener(mListener);

                    mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_FACE_MANAGE, "1");
                    //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.HIK_FRA_KEY_NEED_FQFL, "1");
                    //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.HIK_FRA_KEY_LIVE, "0.6");
                    //人脸缓冲区大小默认100000张；
                    mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_POOL_KEY_CAP, "10000");
                    //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_MULTI_THREAD, "1");
                    //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_EXT_RGB_BUFF, "1");
                    //初始化建模模型
                    int init = mFRAProc.init(640, 480, HikFRAAPI.YUV_FORMAT.YUV_NV21, mModelPath);
                    Log.i(TAG, "mFRAProc.init : "+init);
                    //设置旋转角度，角度错误会导致识别失败
                    mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_270);*/
                //延迟后就不会出问题,所以说明必须surfaceView的holder View创建后才能去openCamera
                Log.d(TAG, "startCamera");

                //此处延时启动是因为海康的手机在屏幕黑了但是没有跳出锁屏界面的时候,点击电源键,surfaceCreated不会被调用,只能通过延迟去解决这个bug，华为手机上不会有这个问题
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mCamHandle = new CameraHandle(mContex, mPrevSurface, mFRAProc, mFaceRect,cameraId);

                //启动人脸算法
                mCamHandle.startProc(imageDateInter);


                //在屏幕黑了但是没有跳出锁屏界面的时候,点击电源键,surfaceCreated不会被调用
             /*   mPrevSurface.getHolder().addCallback(new SurfaceHolder.Callback() {
                    @Override
                    public void surfaceCreated(SurfaceHolder holder) {
                        Log.d(TAG, "surfaceCreated");
                        mCamHandle = new CameraHandle(mContex, mPrevSurface, mFRAProc, mFaceRect);

                        //启动人脸算法
                        mCamHandle.startProc(imageDateInter);

                        mPrevSurface.getHolder().removeCallback(this);//移除当前回调

                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                        Log.d(TAG, "surfaceChanged");
                    }

                    @Override
                    public void surfaceDestroyed(SurfaceHolder holder) {
                          *//*  mPrevSurface.getHolder().removeCallback(this);
                            mCamera.setPreviewCallback(null);
                            mCamera.stopPreview();
                            mCamera.release();
                            mCamera = null;*//*
                    }
                });*/


                //开始请求
                //new WorkUtils().startTimer(mFRAProc);

            }
        }).start();
        //mStartBT.setClickable(false);

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.start: {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "start Camera preview!");
                        mPrevSurface = (SurfaceView) findViewById(R.id.surfaceView);
                        mFRAProc = new HikFRAAPI();
                        mListener = new FRAListener();
                        mFRAProc.setListener(mListener);

                        mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_FACE_MANAGE, "1");
                        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.HIK_FRA_KEY_NEED_FQFL, "1");
                        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.HIK_FRA_KEY_LIVE, "0.6");
                        //人脸缓冲区大小默认100000张；
                        mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_POOL_KEY_CAP, "10000");
                        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_MULTI_THREAD, "1");
                        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_EXT_RGB_BUFF, "1");
                        //初始化建模模型
                        int init = mFRAProc.init(640, 480, HikFRAAPI.YUV_FORMAT.YUV_NV21, mModelPath);
                        Log.i(TAG, "mFRAProc.init : " + init);
                        //设置旋转角度，角度错误会导致识别失败
                      /*  public static final String ROTATION_0 = "0";
                        public static final String ROTATION_90 = "90";
                        public static final String ROTATION_180 = "180";
                        public static final String ROTATION_270 = "270";*/
                        //mFRAProc.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_270);
                        mCamHandle = new CameraHandle(mContex, mPrevSurface, mFRAProc, mFaceRect,cameraId);
                        File file = new File(StringUtils.FilePath);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        //加载人脸数据库到缓冲区，即可实现1VN。
                        mFRAProc.loadFaceData(1, StringUtils.FilePath, "/sdcard/facelib/database.bin", "facetest");

                        //启动人脸算法
                        mCamHandle.startProc(imageDateInter);
                        //开始请求
                        WorkUtils.getInstance(mContext).startTimer(mFRAProc);
                        //遍历上传失败的文件
                        WorkUtils.getInstance(mContext).startUpLoadForFail();
                    }
                }).start();
                //mStartBT.setClickable(false);
                break;
            }
            case R.id.capture:
                Intent intent1 = new Intent(MainActivity.this, MyPhotoActivity.class);
                startActivity(intent1);
/*                if (mCamHandle != null) {
                    mCamHandle.switchCamera();
                    break;
                }*/
//                int faceDelModel = mFRAProc.faceDelModel("facetest", "刘德华", "刘德华", "/sdcard/facelib/database.bin");
//                Log.e(TAG, "faceDelModel"+faceDelModel);
                break;
            case R.id.addface:
                if (mCamHandle != null) {
                    Log.d(TAG, "Add face!");
                    mCamHandle.capData(mFaceAddShow);
                    final EditText inputServer = new EditText(MainActivity.this);
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("输入人员名称");
                    builder.setIcon(android.R.drawable.ic_dialog_info);
                    builder.setView(inputServer);
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mFaceAddShow.setImageBitmap(null);
                        }
                    });
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String humId = inputServer.getText().toString();
                            if (humId.isEmpty()) {
                                Log.e(TAG, "input is null");
                                Toast.makeText(MainActivity.this, "输入人员名称错误！", Toast.LENGTH_SHORT).show();
                            } else {
                                Log.d(TAG, "humId = " + humId);
                                String facePath = "/sdcard/facelib/" + humId + ".jpg";
                                mCamHandle.addFaceModel("facetest", humId, humId, facePath, "/sdcard/facelib/database.bin");
                            }
                            mFaceAddShow.setImageBitmap(null);
                        }
                    });
                    builder.show();
                    break;
                }
            case R.id.show: {
                Log.d(TAG, "Show face lib................");
                Intent intent = new Intent(MainActivity.this, FaceLibShow.class);
                startActivity(intent);
                //mFRAProc = new HikFRAAPI();
                //mFRAProc.faceTest();
                break;
            }
            default:
                break;
        }
    }


    class FRAListener implements HikFRAAPI.ListenerCallBack {

        @Override
        public void MsgNotify(int msgType, String msgData, int len) {
            Log.d(TAG, "MsgType: " + msgType + " msgData: " + msgData + " len: " + len);
            if (msgType == HikFRAAPI.FRA_RESULT_INDEX.FRA_RESULT_FC) {
                Message msg = new Message();
                msg.what = MSGCB_FC;
                msg.obj = msgData;
                handler.sendMessage(msg);
            } else if (msgType == HikFRAAPI.FRA_RESULT_INDEX.FRA_RESULT_LS) {
                //区间0-1
                Log.d(TAG, "活体检测可信度" + msgData);
            }
        }

        @Override
        public void DataCallBack(int dataType, byte[] data, String metaData, int len) {
            Log.d(TAG, "dataType: " + dataType + " dataLen: " + data.length + " metaData: " + metaData + " len: " + len);
            if (dataType == HikFRAAPI.FRA_RESULT_INDEX.FRA_RESULT_FR) {
                Log.d(TAG, "HikFRAAPI.FRA_RESULT_INDEX.FRA_RESULT_FR");
                String[] sArray = metaData.split("#");
                mCurFaceBm = mCamHandle.nv21ToBitmap(data, Integer.parseInt(sArray[0]), Integer.parseInt(sArray[1]));
                Message msg = new Message();
                msg.what = MSGCB_FR;
                msg.obj = metaData;
                handler.sendMessage(msg);
            }
        }
    }

    private static final int RC_LOCATION_GPS_PREM = 124;

    private void allocPermission(String[] PERMISSIONS_ALLOC) {
        //循环申请字符串数组里面的权限
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (EasyPermissions.hasPermissions(this, PERMISSIONS_ALLOC)) {
                for (int i = 0; i < PERMISSIONS_ALLOC.length; i++) {
                    switch (PERMISSIONS_ALLOC[i]) {
                        case Manifest.permission.CAMERA:
                            Log.d(TAG, "hasPermissions READ_EXTERNAL_CAMERA");
                            startCamera();
                            break;
                        case Manifest.permission.READ_EXTERNAL_STORAGE:
                            Log.d(TAG, "hasPermissions READ_EXTERNAL_STORAGE");
                            init();
                            break;
                        case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                            LitePal.getDatabase();
                            //子线程去后台同步
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    WorkUtils.getInstance(mContext).startTimer(mFRAProc);
                                    Log.d(TAG, "hasPermissions WRITE_EXTERNAL_STORAGE");
                                }
                            }).start();
                            //遍历上传失败的文件
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    WorkUtils.getInstance(mContext).startUpLoadForFail();
                                    Log.d(TAG, "hasPermissions WRITE_EXTERNAL_STORAGE");
                                }
                            }).start();
                            break;
                        default:
                            break;
                    }
                }
            } else {
                for (int i = 0; i < PERMISSIONS_ALLOC.length; i++) {
                    switch (PERMISSIONS_ALLOC[i]) {
                        case Manifest.permission.CAMERA:
                            EasyPermissions.requestPermissions(MainActivity.this,
                                    "权限申请",//使用官方提供的弹窗(`AppSettingsDialog`)的时候会用到这个字符串,作为用户拒绝之后弹窗的内容
                                    RC_LOCATION_GPS_PREM,
                                    new String[]{Manifest.permission.CAMERA}
                            );
                            //EasyPermissions.requestPermissions(new String[]{Manifest.permission.CAMERA});
                            Log.d(TAG, "allocPermission Manifest.permission.CAMERA");
                            break;
                        case Manifest.permission.READ_EXTERNAL_STORAGE:
                            //allocPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});
                            EasyPermissions.requestPermissions(MainActivity.this,
                                    "权限申请",//使用官方提供的弹窗(`AppSettingsDialog`)的时候会用到这个字符串,作为用户拒绝之后弹窗的内容
                                    RC_LOCATION_GPS_PREM,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}
                            );
                            Log.d(TAG, "allocPermission READ_EXTERNAL_STORAGE");
                            //init();
                            break;
                        case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                            //allocPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
                            EasyPermissions.requestPermissions(MainActivity.this,
                                    "权限申请",//使用官方提供的弹窗(`AppSettingsDialog`)的时候会用到这个字符串,作为用户拒绝之后弹窗的内容
                                    RC_LOCATION_GPS_PREM,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
                            );
                            Log.d(TAG, " allocPermission WRITE_EXTERNAL_STORAGE");
                            break;
                        default:
                            break;

                    }
                }
            }


          /*  else {
                EasyPermissions.requestPermissions(this,
                        "你拒绝了权限",//使用官方提供的弹窗(`AppSettingsDialog`)的时候会用到这个字符串,作为用户拒绝之后弹窗的内容
                        RC_LOCATION_GPS_PREM,
                        PERMISSIONS_ALLOC);
            }*/


           /* //如果没有授权的权限就去请求权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, PERMISSIONS_ALLOC, 1);
            }*/
        }
    }

    private void allocCameraPermission(String[] strings) {
        //循环申请字符串数组里面的权限
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            //如果没有授权的权限就去请求权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 2);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将结果交由EasyPermissions解决
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    //申请失败,申请一组权限的时候,有的会失败
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == RC_LOCATION_GPS_PREM) {
            //权限拒绝，gg
            Toast.makeText(mContext, "权限拒绝", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    //申请成功
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == RC_LOCATION_GPS_PREM) {
            for (int i = 0; i < perms.size(); i++) {
                switch (perms.get(i)) {
                    case Manifest.permission.CAMERA:
                        Log.d(TAG, "onPermissionsGranted READ_EXTERNAL_CAMERA");

                        startCamera();
                        break;
                    case Manifest.permission.READ_EXTERNAL_STORAGE:
                        Log.d(TAG, "onPermissionsGranted READ_EXTERNAL_STORAGE");
                        init();
                        break;
                    case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                        LitePal.getDatabase();
                        WorkUtils.getInstance(mContext).startTimer(mFRAProc);
                        Log.d(TAG, "onPermissionsGranted WRITE_EXTERNAL_STORAGE");
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private class DeviceOrientationListion extends OrientationEventListener {

        public DeviceOrientationListion(Context context) {
            super(context);
        }

        public DeviceOrientationListion(Context context, int rate) {
            super(context, rate);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
                return;
            }

            int newOrientation = ((orientation + 45) / 90 * 90) % 360;
            // Log.d(TAG, "++++++++++++++++++++: onOrientationChanged: " + orientation + " new: " + newOrientation);
            if (mDeviRotation != newOrientation) {
                //   Log.d(TAG, "Device Rotation Change :" + mDeviRotation + " ->" + newOrientation);
                mDeviRotation = newOrientation;
                if (mCamHandle != null) {
                    if (mDeviRotation == 0) {
                        mCamHandle.setRotation(270);
                    } else if (mDeviRotation == 270) {
                        mCamHandle.setRotation(0);
                    }
                }
            }
        }
    }



    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mFRAProc != null) {
            mFRAProc.deInit();
        }
        WorkUtils.getInstance(mContext).stopTimer();
    }


}
